import os
import pandas as pd
from loguru import logger

from models.stock_model import StockNumber, DayInfo


def get_all_stock(today_str, N, stock):
    df_all_stocks = pd.read_csv('../../all.csv')
    count = 0
    for row_index in df_all_stocks.index:
        if stock and df_all_stocks.loc[row_index]['ts_code'] != stock:
            continue
        sn = StockNumber(df.loc[row])
        if '退' in sn.name:
            continue
        if 'ST' in sn.name:
            continue
        if not str(sn.ts_code).startswith('60') \
                and not str(sn.ts_code).startswith('00'):
            continue
        count += 1
        logger.info(f'{sn.ts_code},{sn.name}')
        analysis_stock(today_str, N, sn)


def analysis_stock(today_str, N, sn):
    csv_path = f'stocks/{sn.ts_code}.csv'
    df2 = pd.read_csv(csv_path)
    q10 = []
    q10_di = []
    q11 = []
    q11_di = []
    all_di = []
    parr = 0
    today_di = None
    cnt_max = 0
    cnt_min = 0
    pct_arr = []
    arr_high = []
    arr_high_di = []
    arr_low = []
    arr_low_di = []
    date_arr = []
    price_arr = []
    delta_days = []
    delta_d = 0
    price_arr_high = []
    price_arr_low = []
    for row2 in df2.index:
        if today_di is not None and today_di.close < 10:
            logger.warning(f'{today_di.name}价格低于10')
            return
        delta_d += 1
        di = DayInfo(sn, df2.loc[row2])
        di.name = sn.name
        di.ts_code = sn.ts_code
        di.industry = sn.industry
        # di.trade_date = df2.loc[row2]['trade_date']
        # di.open = df2.loc[row2]['open']
        # di.high = df2.loc[row2]['high']
        price_arr_high.append(di.high)
        # di.low = df2.loc[row2]['low']
        price_arr_low.append(di.low)
        # di.close = float(df2.loc[row2]['close'])
        if di.close < 5:
            break
        if cnt_min > 3 and arr_low_di[0].low > arr_low_di[1].low > arr_low_di[2].low:
            link_code_arr = sn.ts_code.split('.')
            link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
            hyperlink = f'"https://xueqiu.com/S/{link_code}"'
            msg_low = f'{hyperlink},{today_di.ts_code},{today_di.name},{today_di.trade_date},{today_di.close},{arr_low_di[0].trade_date},{arr_low_di[1].trade_date},{arr_low_di[2].trade_date}'
            logger.success(f'{msg_low} 价格接近支撑点')
            with open(f'support_{today_str}.csv', 'a+') as f_low:
                f_low.write(f'{msg_low}\n')
            break
        # di.pre_close = df2.loc[row2]['pre_close']
        # di.change = df2.loc[row2]['change']
        # di.pct_chg = float(df2.loc[row2]['pct_chg'])
        # di.vol = df2.loc[row2]['vol']
        # di.amount = df2.loc[row2]['amount']
        if len(q10) == N * 2 + 1:
            ad = all_di[N]
            if max(q10) == q10[N]:
                arr_high_di.append(q10_di[N])
                delta_days.append(-delta_d) if delta_days else delta_days.append(-(delta_d - 6))
                delta_d = 0
                pct = round((parr - q10[N]) / q10[N] * 100, 2)
                pct_arr.append(pct)
                if pct > 0:
                    arr_high.append(pct)
                else:
                    arr_low.append(pct)
                price_arr.append(q10[N])
                date_arr.append(ad.trade_date)
                parr = q10[N]
                cnt_max += 1
            elif min(q11) == q11[N]:
                arr_low_di.append(q11_di[N])
                pct = round((parr - q11[N]) / q11[N] * 100, 2)
                pct_arr.append(pct)
                if pct > 0:
                    delta_days.append(delta_d) if delta_days else delta_days.append(delta_d - 6)
                    arr_high.append(pct)
                else:
                    delta_days.append(-delta_d) if delta_days else delta_days.append(-(delta_d - 6))
                    arr_low.append(pct)
                delta_d = 0
                price_arr.append(q11[N])
                date_arr.append(ad.trade_date)
                parr = q11[N]
                cnt_min += 1
            all_di.pop(0)
            q10.pop(0)
            q10_di.pop(0)
            q11.pop(0)
            q11_di.pop(0)
        all_di.append(di)
        q10.append(di.high)
        q10_di.append(di)
        q11.append(di.low)
        q11_di.append(di)
        if today_di is None:
            parr = di.low
            today_di = di
            price_arr.append(di.low)
            date_arr.append(di.trade_date)


def printNumber(today_str, stocks, N):
    for stock in stocks:
        get_all_stock(today_str, N, stock)


if __name__ == '__main__':
    bkd = 0
    N = 5


    def msg_filter(msg):
        def is_msg(record):
            return msg in record['message']

        return is_msg


    stocks = [
        ''
    ]
    log_dir = os.path.abspath(__file__).replace('.py', '')
    if not os.path.exists(log_dir):
        os.mkdir(log_dir)

    fpath = f'{log_dir}/support.txt'
    if os.path.exists(fpath):
        os.remove(fpath)
    logger.add(fpath)
    logger.info('生成csv start')

    df = pd.read_csv('../../stocks/000001.SZ.csv')
    all_trade_date_arr = []
    for row in df.index:
        all_trade_date_arr.append(df.loc[row]['trade_date'])

    t_arr = []
    for idx, trade_date in enumerate(all_trade_date_arr):
        if idx > bkd:
            break
        today_str = str(trade_date)
        try:
            printNumber(today_str, stocks, N)
        except Exception as e:
            logger.error(e)
    logger.info('生成 support excel运行完成')
